using System.Text;
using System.Xml.Linq;
using Engine;
using Engine.Input;
using Game;
using XmlUtilities;

namespace SCIENEW.Tech {
    public static class TechTreeManager {
        public static TechTree TechTree { get; private set; } = new();

        public static void Init() {
            ScreensManager.AddScreen("TechTree", new TechTreeScreen());

            XElement? xTechTree = null;
            IndustrialModLoader.GetFile("IndustrialMod.tch", stream => { xTechTree = XmlUtils.LoadXmlFromStream(stream, Encoding.UTF8, true); });
            if (xTechTree != null) DecodeTechTree(xTechTree);
        }

        public static void DecodeTechTree(XElement xTechTree) {
            foreach (var xElement in xTechTree.Elements()) {
                if (xElement.Name == "Node") {//节点
                    string name = XmlUtils.GetAttributeValue<string>(xElement, "Name");
                    TechNode techNode = TechTree.GetOrCreateNode(name);
                    techNode.IconBlock = IECraftingRecipesManager.FindBlocksByCraftingId(XmlUtils.GetAttributeValue<string>(xElement, "Icon"))[0];
                    techNode.Stage = XmlUtils.GetAttributeValue<int>(xElement, "Stage");
                    techNode.DisplayName = XmlUtils.GetAttributeValue<string>(xElement, "DisplayName");
                    techNode.Description = XmlUtils.GetAttributeValue<string>(xElement, "Description");
                    techNode.LayoutOffset = XmlUtils.GetAttributeValue<Vector2>(xElement, "LayoutOffset", Vector2.Zero);
                }

                if (xElement.Name == "Dependencies") {
                    string name = XmlUtils.GetAttributeValue<string>(xElement, "Name");
                    //加载依赖
                    string value = xElement.Value;
                    if (!string.IsNullOrEmpty(value)) {
                        string[] dependencies = value.Split("\n", StringSplitOptions.RemoveEmptyEntries);
                        for (int i = 0; i < dependencies.Length; i++) {
                            dependencies[i] = string.Join("", dependencies[i].Split(default(string[]), StringSplitOptions.RemoveEmptyEntries));
                        }
                        dependencies = dependencies.Where(x => !string.IsNullOrEmpty(x)).ToArray();
                        TechTree.AddDependency(name, dependencies);
                    }
                }
            }
        }

        /// <summary>
        /// 恢复科技树至默认状态
        /// </summary>
        public static void ResumeToDefault() {
            TechTree.LockAllNodes();
        }

        public static void Update() {
        }
    }
}